package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.share.common.core.exception.ServiceException;
import com.share.device.domain.PowerBank;
import com.share.device.mapper.PowerBankMapper;
import com.share.device.service.IPowerBankService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 充电宝表 服务实现类
 * </p>
 *
 * @author pww
 * @since 2025-03-24
 */
@Service
public class PowerBankServiceImpl extends ServiceImpl<PowerBankMapper, PowerBank> implements IPowerBankService {

    @Autowired
    private PowerBankMapper powerBankMapper;

    /**
     * 查询充电宝列表
     *
     * @param powerBank
     * @return
     */
    @Override
    public List<PowerBank> selectPowerBankList(PowerBank powerBank) {

        return powerBankMapper.selectPowerBankList(powerBank);
    }


    /**
     * 新增充电宝
     *
     * @param powerBank
     * @return
     */
    @Override
    public int savePowerBank(PowerBank powerBank) {
        //查询相同编号的充电宝适否存在
        long result = this.count(new LambdaQueryWrapper<PowerBank>().eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo()));
        if (result > 0) {
            throw new ServiceException("该编号的充电宝已存在");
        }
        powerBankMapper.insert(powerBank);
        return 1;
    }


    /**
     * 更新充电宝
     * @param powerBank
     * @return
     */
    @Override
    public int updatePowerBank(PowerBank powerBank) {
        //判断充电宝适否存在
        PowerBank oldPowerBank = this.getById(powerBank.getId());
        if (null != oldPowerBank && !"0".equals(oldPowerBank.getStatus())) {
            throw new ServiceException("该充电宝已投放，无法修改");
        }
        //判断柜机编号是否改变
        if (!oldPowerBank.getPowerBankNo().equals(powerBank.getPowerBankNo())) {
            //通过柜机编号查询柜机是否存在
            long count = this.count(new LambdaQueryWrapper<PowerBank>().eq(PowerBank::getPowerBankNo, powerBank.getPowerBankNo()));
            //如果柜机编号存在 则抛出异常
            if (count > 0) {
                throw new ServiceException("该编号的充电宝已存在");
            }
        }
        powerBankMapper.updateById(powerBank);
        return 1;
    }
}
